#!/usr/bin/perl

use Data::Dumper; 

%t = {};

{
	local $/ = '%%';
	while (<templates/*>) {
		open(T, $_);
		s/^templates\///;
		$t = $_;
		my @a = ();
		while (<T>) {
			chomp;
			push @a, $_ 
		}
		close T;
		$t{$t} = \@a;
	}
}

@m = map {
	s/^modules\/(.*).h$/$1/;
	$_
} <modules/*.h>;

print "modules:\n";
print "\t$_\n" for @m;

for my $m (@m) {
	$mod_o .= fill($t{'mod_o.makefile'}, {name => $m});
	$mod_h .= fill($t{'mod_h.makefile'}, {name => $m});
	$modules .= fill($t{'module.makefile'}, {name => $m});
	$includes .= fill($t{'include.h'}, {name => $m});
	$snippets .= fill($t{'snippet.c'}, {name => $m});
}
$mod_h =~ s/\s+/ /gs;
$mod_o =~ s/\s+/ /gs;

open F, ">Makefile";
print F fill($t{'Makefile'}, {
	mods_o	=> $mod_o,
	mods_h	=> $mod_h,
	modules => $modules,
});
close F;

open F, ">modules.c";
print F fill($t{'modules.c'}, {snippets => $snippets});
close F;

open F, ">modules.h";
print F fill($t{'modules.h'}, {includes => $includes});
close F;


sub fill {
	my ($t, $v) = @_;
	my $o = '';

	my $i = 0;
	for (@$t) {
		$i = ! $i;
		$o .= ($i ? $_ : $v->{$_})
	}
	$o
}
